function refresh() {
    ajaxSendHelper('lobby', '');
}

function getOptionHtml(id, display, checked) {
    if (checked)
        return "<td class='choosemany'><input type='checkbox' id='"+id+"' name='deckName' checked='checked' value='"+display+"'/> <label for='"+id+"'><span class='simpleHtmlCard option_class'><b>"+display+"</b></span> </label></td>";
    else
        return "<td class='choosemany'><input type='checkbox' id='"+id+"' name='deckName'                   value='"+display+"'/> <label for='"+id+"'><span class='simpleHtmlCard option_class'><b>"+display+"</b></span> </label></td>";
}

function getCardHtml(pile, i) {
    if (pile.length > i) 
        return "<td class='choosemany'><input type='checkbox' id='"+pile[i].name+"' name='Card' value='"+ pile[i].name+"' /><label for='" +pile[i].name+ "'>" + card2html(pile[i]) + "</label></td>";
    else
        return "<td></td>";
}


function setCards(data) {
    htmldata = ""
	
    htmldata += "<br><table><tr class='top row'>";
    htmldata += getOptionHtml('deckNameBasic','Basic', true);
    htmldata += getOptionHtml('deckNameIntrigue','Intrigue', true);
    htmldata += getOptionHtml('deckNameCornucopia','Cornucopia', true);
    htmldata += getOptionHtml('deckNameProsperity','Prosperity', true);
    htmldata += getOptionHtml('deckNameSeaside','Seaside', true);
    htmldata += getOptionHtml('deckNameAlchemy','Alchemy', true);
    htmldata += getOptionHtml('deckNameHinterlands','Hinterlands', true);
    htmldata += getOptionHtml('deckNameDarkAges','DarkAges', true);
	htmldata += getOptionHtml('deckNameGuilds','Guilds', true);
    htmldata += getOptionHtml('deckNameAddiction','Addiction', true);
    htmldata += getOptionHtml('deckNamePromotion','Promotion', true);
    //htmldata += getOptionHtml('deckNameHolyGrail','HolyGrail', false);
    htmldata += "</tr>";
	
    maxLen = data.cards.darkages.length;
    for ( var i=0, len=maxLen; i<len; ++i ){
		
        htmldata += "<tr>";
		
        htmldata += getCardHtml(data.cards.basic, i);
        htmldata += getCardHtml(data.cards.intrigue, i);
        htmldata += getCardHtml(data.cards.cornucopia, i);
        htmldata += getCardHtml(data.cards.prosperity, i);
        htmldata += getCardHtml(data.cards.seaside, i);
        htmldata += getCardHtml(data.cards.alchemy, i);
        htmldata += getCardHtml(data.cards.hinterlands, i);
        htmldata += getCardHtml(data.cards.darkages, i);
		htmldata += getCardHtml(data.cards.guilds, i);
		htmldata += getCardHtml(data.cards.addiction, i);
		htmldata += getCardHtml(data.cards.promotion, i);
        //htmldata += getCardHtml(data.cards.holygrail, i);
		
        htmldata += "</tr>"
    }	
    htmldata += "</table>";
    return htmldata
}

function setPlayersAndCards(data) {
	
    var sec_players = document.getElementById('sec_players');
    htmldata ="<b>Welcome "+data.id+" </b>"
	
    if (data.users) {
        htmldata += "<form id ='gamefrm' name='invitefrm' action='javascript:invite()'>"
	
	
		
        var ulen = data.users.length;
        for ( var i=0, len=ulen; i<len; ++i ){
            var u = data.users[i];
            if (data.id != u.name)
                htmldata += "<input type='checkbox' name='Player' value='"+u.name+"' />"+u.name+" ("+u.level+")<br>";
        }
		//htmldata += "<br><a href=\"log.php\" id='gameloglink'> Game Logs </a>";
        htmldata += "<br><input type='submit' value='Invite / Start Game'/><br></form>";
		htmldata += "<button onclick=\"window.open('log.php', '_blank');\">Game Logs</button>";
		
    }
    sec_players.hidden = false;
    sec_players.innerHTML = htmldata;
	
    //we do not set cards if the lobby already set
    if (isLobbySet)
        return
		
    var sec_cards = document.getElementById('sec_cards');
    htmldata = "";
    htmldata += "<form>Preset Games: ";
    htmldata += "<select id='pGames' onchange='javascript:presetGames()'>";
    htmldata += "<option>All</option>";
    htmldata += "<option>Basic</option>";
    htmldata += "<option>Advanced</option>";
    htmldata += "<option>Official</option>";
    htmldata += "</select></form>";

    htmldata += "<table><tr>";
    htmldata += getOptionHtml('forceColony', 'Colony Game', false);
    htmldata += getOptionHtml('forceDarkAges', 'Dark Ages Game', false);
    htmldata += "</tr></table>";
	
    htmldata += setCards(data);
	
    sec_cards.innerHTML = htmldata;
}

function setGames(data) {

    var sec_games = document.getElementById('sec_games');
    htmldata = "";
	
    var glen = data.allGames.length;
    for ( var i=0, len=glen; i<len; ++i ){
        var gid = data.allGames[i];
        htmldata += "<a href=\"index.php?cmd=loadgame&gid="+gid+"\">"+gid+"</a></br>";	
    }
    sec_games.innerHTML = htmldata;
}

function setTrailer(data) {
    var sec_trailer = document.getElementById('sec_trailer');
    htmldata = "";
    htmldata += "<form action='index.php' method='post'>";
    htmldata += "<input type='hidden' name='cmd' value='logout' />"
    htmldata += "<input type='submit' name='SubmitForm' value='Logout' /></form>"
	
    sec_trailer.innerHTML = htmldata;
}

function generateChat(data) {

	var chatwindow = document.getElementById('chatwindow');
	var htmldata = ""
	
	var alen = data.chat.lines.length;
	var lastid = 0;
	for ( var i=0, len=alen; i<len; ++i ){
		htmldata += "<b>" + data.chat.lines[i].name +":</b> "+data.chat.lines[i].line+"<br>";
		lastid = data.chat.lines[i].id;
	}
	document.getElementById('last_chat_id').title = lastid;
	chatwindow.innerHTML = htmldata; 

	$('#line').autosize({append: "\n"})
	$('#chatwindow').prop("scrollTop", $("#chatwindow").prop('scrollHeight'));
	$('#chatfrm').keypress(function (e) {	
	  if (e.which == 13) {
		e.preventDefault();
		$('#chatfrm').submit();
	  }
	});
}

function updateChatLines(data) {
	if (data.modifications == false)
		return;
	var last_chat_id = document.getElementById('last_chat_id').title;
	var chatwindow = document.getElementById('chatwindow');
	if (!chatwindow)
		return;
	var innerHtml = chatwindow.innerHTML;
	var alen = data.chat.lines.length;
	var last_id = last_chat_id;
	for ( var i=0, len=alen; i<len; ++i ){
		
		if (parseInt(data.chat.lines[i].id) > last_id) {
			innerHtml += "<b>" + data.chat.lines[i].name +":</b> "+data.chat.lines[i].line+"<br>";
			last_id = parseInt(data.chat.lines[i].id);
		}
	}
	
	if (last_chat_id != last_id)
		ChatAlertMe();
	document.getElementById('last_chat_id').title = last_id;
	chatwindow.innerHTML = innerHtml;
	$('#chatwindow').prop("scrollTop", $("#chatwindow").prop('scrollHeight'));
}

function generateScreen(data) {
    sec_screen = document.getElementById('sec_screen');
    var htmldata = "";
    var alen = data.screenmessages.lines.length;
    for ( var i=0, len=alen; i<len; ++i ){
        htmldata += data.screenmessages.lines[i].name+": "+data.screenmessages.lines[i].line+"<br>";
    }
    sec_screen.innerHTML = htmldata;
}

function generateInput(data) {
    var alen = data.input.params.length;
    if (alen == 0)
        return;
    sec_options = document.getElementById('sec_options');
    sec_options.hidden = false;
    htmldata = "<table><tr><td>"+data.input.screen+"</td></tr><tr><td>";
    var alen = data.input.params.length;
    for ( var i=0, len=alen; i<len; ++i ){
	
        //htmldata += "<input type='radio' name='1' id='"+i+"' value='"+data.input.params[i]+"'/>"+data.input.params[i];
        htmldata += "<input type='hidden' name='1' id='"+i+"' value='"+data.input.params[i]+"'/>"
        htmldata += "<span style='color:blue;cursor:pointer;'  onclick='playSingleInput("+i+")'>"+data.input.params[i]+"</span>&nbsp;&nbsp;";
    }
    //htmldata += "</td><td><input type='button' onclick='playInput("+alen+")' value='Ok' /></td></tr></table>"
    htmldata += "</td></tr></table>"
    htmldata += "<input type='hidden' id='mincheckbox' value='"+data.input.min+"' />";
    htmldata += "<input type='hidden' id='maxcheckbox' value='"+data.input.max+"' />";
    sec_options.innerHTML = htmldata;
}

isLobbySet = false
function setData(data) {
	
    if (data.roomid > 0) {
        window.location = "ingame.html";
        return;
    }
    var f_uniqueid = document.getElementById('uniqueid');
    var current_uniqueid = f_uniqueid.title;
    var new_uniqueid = data.uniqueid;
    if (current_uniqueid != new_uniqueid) {
        f_uniqueid.title = new_uniqueid;
        f_uniqueid.innerHTML = new_uniqueid;
        setLobby(data)
    }
    isLobbySet = true;
}

	
function setLobby(data) {

    document.title = "Dominion";
    if (data.alertPlayer)
        AlertMe();
		
    setPlayersAndCards(data);
    //setGames(data);
    setTrailer(data);
    generateChat(data);
    //generateScreen(data);
    generateInput(data);
	
	
    // Add tool tips to cards
    $(".hastooltip").tooltip( {
        predelay: 1250
    });
    $(".hastooltip").dynamic();
}

function AlertMe() {

    document.getElementById("sec_sound").innerHTML="<embed src='sounds/s1.mp3' hidden='true' autostart='true' loop='false' />";
	
    var oldTitle = document.title;
    var msg = "Alarm! Alarm!";
    var timeoutId = setInterval(function() {
        document.title = document.title == msg ? ' Dominion' : msg;
    }, 750);
    window.onmousemove = function() {
        clearInterval(timeoutId);
        document.title = oldTitle;
        window.onmousemove = null;
    };
}

function ChatAlertMe() {

	document.getElementById("sec_sound").innerHTML="<embed src='sounds/s2.mp3' hidden='true' autostart='true' loop='false' />";
 
}

function trim (str)
{
    return str.replace (/^\s+|\s+$/g, '');
}

function addChatLine() {
    chatForm = document.getElementById('chatfrm');
    line =  chatForm.line.value
	chatForm.line.value = "";
    if (trim(line) != '')
    {
		line = encodeURIComponent(line);
        ajaxSendHelper('addChatLine',"&line="+line);
    }
}

function getGameParams(withPlayers) {
    var params = "";
	
    deckNames = document.getElementsByName('deckName');
    alen = deckNames.length;
    for (var i=0, len=alen; i<len; ++i ){
        x = deckNames[i];
        params += "&"+x.value+"="+x.checked;
    }
	
    cards = document.getElementsByName('Card');
    alen = cards.length;
    var choosen = 0;

    for (var i=0, len=alen; i<len; ++i ){
        x = cards[i];
        if (x.checked) {
            params += "&Card_"+choosen+"="+x.value;
            choosen += 1;
        }
    }
	
    if (withPlayers == true) {
        players = document.getElementsByName('Player');
        alen = players.length;
        choosen = 0;
        for (var i=0, len=alen; i<len; ++i ){
            x = players[i];
            if (x.checked) {
                params += "&Player_"+choosen+"="+x.value;
                choosen += 1;
            }
        }
    }
    forceColony = document.getElementById('forceColony');
    params+="&forceColony="+forceColony.checked;
	
    forceDarkAges = document.getElementById('forceDarkAges');
    params+="&forceDarkAges="+forceDarkAges.checked;
	

    return params;
}

function presetGames() {
    pGames = document.getElementById('pGames');
    option = pGames.options[pGames.selectedIndex].value;

	
    dBasic       = document.getElementById('deckNameBasic');
    dIntrigue    = document.getElementById('deckNameIntrigue');
    dCornucopia  = document.getElementById('deckNameCornucopia');
    dProsperity  = document.getElementById('deckNameProsperity');
    dSeaside     = document.getElementById('deckNameSeaside');   
    dAlchemy     = document.getElementById('deckNameAlchemy');
    dHinterlands = document.getElementById('deckNameHinterlands');
    dDarkAges    = document.getElementById('deckNameDarkAges' );
	dGuilds      = document.getElementById('deckNameGuilds' );
    dAddiction   = document.getElementById('deckNameAddiction');
    dPromotion   = document.getElementById('deckNamePromotion');
    //dHolyGrail   = document.getElementById('deckNameHolyGrail')
	
    deckNames = document.getElementsByName('deckName');
    alen = deckNames.length;
    for (var i=0, len=alen; i<len; ++i ){
        x = deckNames[i];
        x.checked = false;
    }
	
    if (option == 'All') {
        for (var i=0, len=alen; i<len; ++i ){
            x = deckNames[i];
            x.checked = true;
        }
    //dHolyGrail.checked = false;
    }
    else if (option == "Basic") {
        dBasic.checked = true;
    }
    else if (option == "Advanced") {
        dBasic.checked = true;
        dIntrigue.checked = true;
    }
    else if (option == "Official") {
        dBasic.checked = true;
        dIntrigue.checked = true;
        dCornucopia.checked = true;
        dProsperity.checked = true;
        dSeaside.checked = true;
        dAlchemy.checked = true;
        dHinterlands.checked = true;
        dDarkAges.checked = true;
        dPromotion.checked = true;
		dGuilds.checked = true;
    }
}


function invite() {
    var sec_players = document.getElementById('sec_players');
    sec_players.hidden = true;
    var params = getGameParams(true);
    ajaxSendHelper('invite', params);
}

function startGame() {
	
    var params = getGameParams(false);
    ajaxSendHelper('startgame', params);
}

function playSingleInput(i) {
    sec_options = document.getElementById('sec_options');
    sec_options.hidden = true;
    var params = "&roomid=0";
	
    var x = document.getElementById(i);
    for ( var j=0; j<i; ++j ){
        params += "&"+j+"=off";
    }
    params += "&"+i+"="+x.value;
	
    ajaxSendHelper('input', params);
}

function playInput(alen) {

    var params = "&roomid=0";
    var choosen = 0;
    for ( var i=0, len=alen; i<len; ++i ){
        var x = document.getElementById(i);
        if (x.checked) {
            choosen += 1;
            params += "&"+i+"="+x.value;
        }
        else {
            params += "&"+i+"=off";
        }
    }
    var min = document.getElementById("mincheckbox").value;
    var max = document.getElementById("maxcheckbox").value;
    if ((choosen >= min) && (choosen <= max || max == -1)) {
        var sec_options = document.getElementById('sec_options');
        sec_options.innerHTML = "";
        ajaxSendHelper('input', params);
    }
    else {
        alert("Please choose the correct number of options")
    }
}

function getCardClass(card) {

    var cardClass = "";
    if (card.isRuin) {
        cardClass = "card_ruin";
    }
    else if (card.isDuration) {
        cardClass = "card_duration";
    }
    else if (card.isReaction && card.isTreasure) {
        cardClass = "card_reaction_treasure";
    }
    else if (card.isReaction && card.isVictory) {
        cardClass = "card_reaction_victory";
    }
    else if (card.isReaction) {
        cardClass = "card_reaction";
    }
    else if (card.isAction && card.isTreasure) {
        cardClass = "card_action_treasure";
    }
    else if (card.isAction && card.isVictory) {
        cardClass = "card_action_victory";
    }
    else if (card.isTreasure && card.isVictory) {
        cardClass = "card_treasure_victory";
    }
    else if (card.isAction) {
        cardClass = "card_action";
    }
    else if (card.isTreasure) {
        cardClass = "card_treasure";
    }
    else if (card.isVictory) {
        cardClass = "card_victory";
    }
    else if (card.isCurse) {
        cardClass = "card_curse";
    }
    return cardClass;
}

function card2html(card) {
    var card = allCardsArray[card.name];
	
    var hasToolTipClass = ""
    if(card.tooltip != "")
        hasToolTipClass = "hastooltip";
	
    var cardClass = getCardClass(card);
	
    var through = ""
    if (!card.isImplemented)		
        through = "style='text-decoration:line-through;'";
	
    var htmldata = "<span class='simpleHtmlCard " + hasToolTipClass+ " " + cardClass + "' "+through+">" + card.name + "</span>";
	

    // Add description if exist
    if(card.tooltip != "") {
        htmldata += "<div class='tooltip'>" + card.tooltip + "</div>";
    }
	
    return htmldata;
	
}

function ajaxSendHelper(cmd, extradata) {
	
    $.ajax({
        url: "index.php",
        data: "cmd="+cmd+""+extradata,
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data) {
                if (data.redirect != null) {
                    window.location = data.redirect;
                }
                else
                    setLobby(data);
            }
        },
        error: function (xhr, ajaxOptions, thrownError){
			
            var sec_debug = document.getElementById('sec_debug');
            sec_debug.innerHTML = xhr.responseText;
            alert(xhr.responseText);
        }   
    });
}